import { Context } from 'koa'
import * as md5 from 'md5'

export default class AdminController {
    /**
     * tslint:disable-next-line: jsdoc-format
     * @api {POST}        /Administrator/login            登录
     * @apiName           /Administrator/login
     * @apiGroup          Administrator
     * @apiVersion 0.1.0
     * @apiParam          {String}            username    用户名
     * @apiParam          {String}            password    密码
     * @apiSuccessExample Success-Response:
     * {
     * "code": 0,
     * "msg": "登录成功",
     * "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpJ9"2
     * }
     */
    public static async Login(ctx: Context) {
        const { username, password }: userInfo = ctx.request.body;
        const { db } = ctx;

        if (!username) {
           ctx.errors('用户名不能为空');
           return;
        }

        if (!password) {
            ctx.errors('密码不能为空');
            return;
        }

        const condition  = {
            where: {
                username: username,
                password: md5(password)
            },
            attributes: ['id', 'username', 'phone', 'avatar', 'role_id'],
            include: {
                as: 'userinfo',
                required: true,
                model: db.UserInfo,
            }
        };

        const data = await db.Admin.findOne(condition);

        if (!data) {
            ctx.errors('用户名或密码错误');
            return;
        }

        // const { role: { id } } = data;
        // const localToken = ctx.createToken(data, id, '2', 'hours');
        ctx.body = {code: 0, msg: '登录成功', token: 'localToken'};
        console.log(data.dataValues);
    }
}